package com.xj.common.sdk.util;



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;


/**
* @author Crius  E-mail: 291750265@qq.com 
* @version V1.0  创建时间：2021年1月7日 下午6:49:37 
* 类说明 
*/

@Slf4j
@Component
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    //自定义topic
    public static final String TOPIC_TEST = "robot-partol-result";


    public boolean send(String sendStr) {
    	
        //String obj2String = JSONObject.toJSONString(obj);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC_TEST, sendStr);
        boolean[] ok= new boolean[1];
        ok[0]=true;
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
            	ok[0] = false;
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
            	ok[0] = true;
                //log.info(TOPIC_TEST + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
            }
        });
        return ok[0];

    }

    public boolean send(String topic,String sendStr) {

        //String obj2String = JSONObject.toJSONString(obj);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, sendStr);
        boolean[] ok= new boolean[1];
        ok[0]=true;
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                ok[0] = false;
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                ok[0] = true;
                log.info(TOPIC_TEST + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
            }
        });
        return ok[0];

    }
}
